package leetcode.n2022;

/**
 * https://leetcode-cn.com/problems/binary-search/
 *
 * @Author: Chaos
 * @Date: 2022/1/31
 */
public class Search {

    public int search(int[] nums, int target) {

        //第一次最笨的方法
//        for (int i = 0; i < nums.length; i++) {
//            if (nums[i] == target) {
//                return i;
//            }
//        }
//        return -1;

        // 二分查找
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int min = left + ((right - left) / 2);
            if (nums[min] > target) {
                right = min - 1;
            } else  if (nums[min] < target){
                left = min + 1;
            } else {
                return min;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7, 9};
        int target = 1;

        System.out.println(new Search().search(nums, target));
    }
}
